package com.sky.aop;


import com.sky.annotation.AutoFilled;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFilled)")
    public void autoFillPointCut(){}

    /**
     * 环绕通知，在通知中进行公共字段的赋值
     */
    @Around("autoFillPointCut()&& @annotation(autoFill)")
    public Object autoFill(ProceedingJoinPoint proceedingJoinPoint, AutoFilled autoFill) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs();
        Object pojo = args[0];
        OperationType value = autoFill.value();
        Class aClass = pojo.getClass();
        if (value == OperationType.INSERT){
            Field creatTime = aClass.getDeclaredField("createTime");
            creatTime.setAccessible(true);
            creatTime.set(pojo, LocalDateTime.now());
            Field createUserField = aClass.getDeclaredField("createUser");
            createUserField.setAccessible(true);
            createUserField.set(pojo, BaseContext.getCurrentId());
        }

        Field updateTime = aClass.getDeclaredField("updateTime");
        updateTime.setAccessible(true);
        updateTime.set(pojo, LocalDateTime.now());
        Field updateUser = aClass.getDeclaredField("updateUser");
        updateUser.setAccessible(true);
        updateUser.set(pojo, BaseContext.getCurrentId());
        Object proceed = proceedingJoinPoint.proceed(args);
        return proceed;
    }


}
